
Imports System.Data.OleDb
Imports System.IO
Imports RIBS.Code.DBCode
Imports RIBS.Code.GlobalModule1
Imports RIBS.BusinessLogicLayer
Imports System.Net

Public Class frmMain
    Enum ScreenState
        AddingRecord
        EditingRecord
        CanEditRecord
        CanAddRecord
        CanAddRecordAndEditRecord
        ViewData
        Loading
    End Enum

    Enum ReturnType
        Main = 0
        Tasks = 1
    End Enum

    Private UserSecurity As String = ""
    Private bEditing As Boolean = False
    Private bEditingCurrent As Boolean = False
    Private dsRibs As New DataSet
    Private dsEditing As New DataSet
    Private bmRibs As BindingManagerBase
    Private MainCaption As String = ""
    Private CurrentActionID As Int32
    Private bSaveGridSetting As Boolean = False
    Dim oSec As New UserSecurity


    Sub ToggleScreenButtonsState(ByVal lScreenState As ScreenState)

        Debug.Print("ScreenState :" & lScreenState.ToString)
        tbSaveRecord.Enabled = False
        btnSaveRecord.Enabled = False
        mnuSave.Enabled = False

        btnAddHistoryRec.Enabled = False
        tbAddHistoryRecord.Enabled = False
        mnuAddRecord.Enabled = False

        btnEditCurrentRecord.Enabled = False
        mnuEditSelected.Enabled = False
        tbEditRecord.Enabled = False

        tbCancelCurrentEdit.Enabled = False
        mnuCancelEdit.Enabled = False

        tbRefresh.Enabled = False
        mnuRefresh.Enabled = False
        tbFilter.Enabled = False
        mnuFilter.Enabled = False

        dgFullList.Enabled = False
        dgTasks.Enabled = False
        dgHistory.Enabled = False

        Select Case lScreenState
            Case ScreenState.AddingRecord
                tbSaveRecord.Enabled = True
                btnSaveRecord.Enabled = True
                mnuSave.Enabled = True
                tbCancelCurrentEdit.Enabled = True
                mnuCancelEdit.Enabled = True

            Case ScreenState.EditingRecord
                tbSaveRecord.Enabled = True
                btnSaveRecord.Enabled = True
                mnuSave.Enabled = True
                tbCancelCurrentEdit.Enabled = True
                mnuCancelEdit.Enabled = True

            Case ScreenState.CanAddRecord
                btnAddHistoryRec.Enabled = True
                tbAddHistoryRecord.Enabled = True
                mnuAddRecord.Enabled = True
                tbRefresh.Enabled = True
                mnuRefresh.Enabled = True
                tbFilter.Enabled = True
                mnuFilter.Enabled = True

                dgFullList.Enabled = True
                dgTasks.Enabled = True
                dgHistory.Enabled = True

            Case ScreenState.CanAddRecordAndEditRecord
                btnAddHistoryRec.Enabled = True
                tbAddHistoryRecord.Enabled = True
                mnuAddRecord.Enabled = True
                btnEditCurrentRecord.Enabled = True
                mnuEditSelected.Enabled = True
                tbEditRecord.Enabled = True
                tbRefresh.Enabled = True
                mnuRefresh.Enabled = True
                tbFilter.Enabled = True
                mnuFilter.Enabled = True

                dgFullList.Enabled = True
                dgTasks.Enabled = True
                dgHistory.Enabled = True

            Case ScreenState.CanEditRecord
                btnEditCurrentRecord.Enabled = True
                mnuEditSelected.Enabled = True
                tbEditRecord.Enabled = True
                tbRefresh.Enabled = True
                mnuRefresh.Enabled = True
                tbFilter.Enabled = True
                mnuFilter.Enabled = True

                dgFullList.Enabled = True
                dgTasks.Enabled = True
                dgHistory.Enabled = True

            Case ScreenState.ViewData
                btnAddHistoryRec.Enabled = True
                mnuAddRecord.Enabled = True
                tbAddHistoryRecord.Enabled = True
                tbRefresh.Enabled = True
                mnuRefresh.Enabled = True
                tbFilter.Enabled = True
                mnuFilter.Enabled = True

                dgFullList.Enabled = True
                dgTasks.Enabled = True
                dgHistory.Enabled = True
            Case ScreenState.Loading

        End Select
    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        gConnectionString = GetdbConnection()
        gConnectionStringArchive = gConnectionString.Replace("RIBS.Mdb", "RIBs_Archive.Mdb")
        'DataBaseTools.BackUpDataBase()
        CurrentDB = My.Settings.AvailableDatabases
        SystemFilter = False
        Try
            TestDBConnection()
        Catch ex As Exception
            If Mid(ex.Message, 1, Len("Could not find file")) = "Could not find file" Then
                Dim oBrows As New OpenFileDialog
                oBrows.Title = "Please Select Database file "
                oBrows.Filter = "Access (*.mdb)|*.mdb"
                oBrows.InitialDirectory = My.Settings.ImportDataFolder
                oBrows.ShowDialog()
                My.Settings.AvailableDatabases = oBrows.FileName
                My.Settings.Save()
            End If
        End Try
        Application.DoEvents()
        Try
            '12/01
            'gsMyMainStates = My.Settings.MyMainStates
            'gsMyTaskStates = My.Settings.MyTaskStates
            gConnectionString = GetdbConnection()
            gConnectionStringArchive = gConnectionString.Replace("RIBS.Mdb", "RIBs_Archive.Mdb")
            CurrentUser = Environ("USERNAME").ToUpper
            NetWorkUserID = Environ("USERNAME")
            CurrentDB = My.Settings.AvailableDatabases
            CurrentPC = Environ("COMPUTERNAME")
            Dim oUser As New dbUser(CurrentUser)
            CheckDbTables()

            oNetworkUser = New NetworkUser(NetWorkUserID)
            GetUserList()
            MainCaption = "RIBS -" & CurrentPC & "\" & CurrentUser & " [" & CurrentDB & "] "
            Text = MainCaption '& " <System Filter>"
            tbFind.Image = ImageList1.Images("Search")
            btnWorkFlow.Image = ImageList1.Images("WorkFlow")
            LoadRipsList()
            ToggleTabContact(False)
            ToggleTabDetail(False)
            If GetMyPublishVersion() <> "" Then

            End If
            TestDBConnection()
            ToggleScreenButtonsState(ScreenState.ViewData)


        Catch ex As Exception
            'ex.Source = "Sub Main"
            DisplayErrors(ex)
        Finally
            Try
                If My.Application.Info.AssemblyName <> "RIBS.01Development" Then
                    Dim oProxy As WebProxy = New WebProxy("http://www.avivaintranet.com.au/proxy/webproxy.pac")
                    oProxy.Credentials = System.Net.CredentialCache.DefaultCredentials
                    'GlobalProxySelection.Select = oProxy
                    'Dim oEmail As New SendMail.SendMail

                    Application.DoEvents()
                    'oEmail.Proxy = oProxy
                    'oEmail.SendSMTPMailAsync("Please", "Logon: " & NetWorkUserID & " (" & GetMyPublishVersion() & ")", Application.ProductName & " " & Application.ProductVersion & " " & GetMyPublishVersion(), "")

                    'oEmail.SendSMTPMail("Please", "Logon: " & NetWorkUserID & " (" & GetMyPublishVersion() & ")", Application.ProductName & " " & Application.ProductVersion & " " & GetMyPublishVersion(), "")
                End If
            Catch ex As Exception
                Debug.Print(ex.Message)
            End Try
        End Try
    End Sub

    Sub GetUserList()
        Dim oUser As New dbUser(CurrentUser)
        tbComBoUsers.Items.Clear()
        tbComBoUsers.Text = CurrentUser
        Dim dt As DataTable = oUser.GetAllUsers()
        For Each dr As DataRow In dt.Rows
            tbComBoUsers.Items.Add(UCase(dr.Item(0)))
        Next
    End Sub

    Sub SelectDataBase()
        Try
            Dim oBrows As New OpenFileDialog
            oBrows.Title = "Please Select Database file "
            oBrows.Filter = "Access (*.mdb)|*.mdb"
            oBrows.InitialDirectory = My.Settings.ImportDataFolder
            oBrows.ShowDialog()
            My.Settings.AvailableDatabases = oBrows.FileName
            My.Settings.Save()

            If Not ValidDataBase(oBrows.FileName) Then
                SelectDataBase()
            End If

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Function ValidDataBase(ByVal lDBName As String) As Boolean
        Try
            lDBName = StrReverse(lDBName)
            lDBName = Microsoft.VisualBasic.Left(lDBName, InStr(lDBName, "\") - 1)
            lDBName = Microsoft.VisualBasic.Mid(lDBName, 5)
            lDBName = StrReverse(lDBName)
            If UCase(lDBName) <> (UCase(My.Application.Info.AssemblyName)) Then
                If MsgBox("Invalid Database! " & vbCrLf & _
                            vbCrLf & _
                            "Application Name =" & My.Application.Info.AssemblyName & vbCrLf & _
                            "Database =" & lDBName, MsgBoxStyle.Critical, "STOP") Then
                    Return False
                End If
            End If
            Return True
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Function TestDBConnection() As Boolean
        Try
            gConnectionString = GetdbConnection()
            gConnectionStringArchive = gConnectionString.Replace("RIBS.Mdb", "RIBs_Archive.Mdb")
            Dim lDB As String() = Split(gConnectionString, ";")
            For Each str As String In lDB
                If InStr(UCase(str), UCase("Data Source="), CompareMethod.Text) Then
                    Dim lDBName As String = Microsoft.VisualBasic.Mid(str, InStr(str, "=") + 1)
                    'RepDataBase(lDBName)
                    lDBName = StrReverse(lDBName)
                    lDBName = Microsoft.VisualBasic.Left(lDBName, InStr(lDBName, "\") - 1)
                    lDBName = Microsoft.VisualBasic.Mid(lDBName, 5)
                    lDBName = StrReverse(lDBName)
                    If UCase(lDBName) <> (UCase(My.Application.Info.AssemblyName)) Then
                        If MsgBox("Invalid Database! " & vbCrLf & _
                                    vbCrLf & _
                                    "Application Name =" & My.Application.Info.AssemblyName & vbCrLf & _
                                    "Database =" & lDBName, MsgBoxStyle.Critical, "STOP") Then
                            gConnectionString = Replace(gConnectionString, lDBName, "")
                            gConnectionStringArchive = gConnectionString.Replace("RIBS.Mdb", "RIBs_Archive.Mdb")
                            SelectDataBase()
                            'Application.Exit()
                            Exit Function
                        End If
                        Exit For
                    End If
                End If
            Next
            Dim oRibs As New RibsClass
            Dim dt As DataTable = oRibs.GetActions
            Return True
        Catch ex As Exception
            Throw ex
        End Try
    End Function


    Sub DisableScreen()
        Try
            For Each cont As Control In Me.Controls
                cont.Enabled = False
                'If TypeOf cont Is TextBox Then
                '    Dim txt As TextBox = cont
                '    txt.ReadOnly = False
                'ElseIf TypeOf cont Is ComboBox Then
                '    Dim com As ComboBox = cont
                '    com.Enabled = False
                'End If
            Next
            dgHistory.Enabled = True
        Catch ex As Exception

        End Try
    End Sub

    Sub EnableScreen()
        Try
            Dim cont As Control
            For Each cont In Me.Controls
                cont.Enabled = True
                'If TypeOf cont Is TextBox Then
                '    Dim txt As TextBox = cont
                '    txt.ReadOnly = True
                'ElseIf TypeOf cont Is ComboBox Then
                '    Dim com As ComboBox = cont
                '    com.Enabled = True
                'End If
            Next
        Catch ex As Exception

        End Try
    End Sub

    Sub ToggleTabDetail(ByVal State As Boolean)
        Try
            dtlDate.Enabled = State
            comStatus.Enabled = State
            'comUser.Enabled = State
            comAction.Enabled = State
            comContactMethod.Enabled = State
            txtNote.Enabled = State
            txtRetained.ReadOnly = Not State
            txtWriteoff.ReadOnly = Not State
            dgHistory.ReadOnly = True
            dgHistory.Enabled = False
            'For Each ct As Control In tabDetail.Controls
            '    'ct.Enabled = State                
            '    If TypeOf ct Is TextBox Then
            '        Dim txt As TextBox = ct
            '        txt.ReadOnly = State
            '        ct = txt
            '    ElseIf TypeOf ct Is ComboBox Then
            '        Dim com As ComboBox = ct
            '        com.Enabled = State
            '        ct = com
            '    End If
            'Next
            btnWorkFlow.Enabled = True
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Sub ToggleTabContact(ByVal State As Boolean)
        Try

            txtPolicyNumber.ReadOnly = Not State
            txtMailingName.ReadOnly = Not State
            txtMailingAddress1.ReadOnly = Not State
            txtMailingAddress2.ReadOnly = Not State
            txtMailingAddress3.ReadOnly = Not State
            txtMailingAddress4.ReadOnly = Not State
            txtMailingAddress5.ReadOnly = Not State
            txtMailingAddress6.ReadOnly = Not State
            txtProductType.ReadOnly = Not State
            comNoticeCode.Enabled = State
            txtSystem.ReadOnly = Not State
            txtAdviserName.ReadOnly = Not State
            txtAdviserNumber.ReadOnly = Not State
            txtAdviserEmail.ReadOnly = Not State
            txtAdviserPhone.ReadOnly = Not State
            txtAmountDue.ReadOnly = Not State
            tpLetterDate.Enabled = State
            dpDueDate.Enabled = State
            txtNewAmount.ReadOnly = Not State
            txtPaymentFreq.ReadOnly = Not State
            txtSuperInd.ReadOnly = Not State

            'For Each ct As Control In tabContact.Controls
            '    'ct.Enabled = State
            '    If TypeOf ct Is TextBox Then
            '        Dim txt As TextBox = ct
            '        txt.ReadOnly = State
            '        ct = txt
            '    ElseIf TypeOf ct Is ComboBox Then
            '        Dim com As ComboBox = ct
            '        com.Enabled = State
            '        ct = com
            '    End If
            'Next
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Sub AddRec()
        Try
            Dim oRibs As New RibsClass
            Dim oUsr As New dbUser
            'Dim dr As DataRow
            dtlDate.Value = Now
            lblReason.Visible = False
            txtNote.Text = ""

            LoadDropDownBoxes()

            comStatus.Text = IIf(IsDBNull(dsRibs.Tables("Ribs").Rows(0).Item("RibsState")), "", dsRibs.Tables("Ribs").Rows(0).Item("RibsState"))
            ToggleTabDetail(True)
            If dsRibs.Tables("Ribs").Rows(0).Item("ManuallyAdded") Then
                ToggleTabContact(True)
                CurrentID = dsRibs.Tables("Ribs").Rows(0).Item("RibsID")
                'Edit()
                bEditing = True
            End If
            ToggleScreenButtonsState(ScreenState.AddingRecord)
            'If CDbl(dsRibs.Tables("Ribs").Rows(0).Item("NEW_PREMIUM_AMOUNT")) > 0 Then
            '    If CDbl(txtRetained.Text) = 0 Then
            '        If CDbl(dsRibs.Tables("Ribs").Rows(0).Item("NEW_PREMIUM_AMOUNT")) <> CDbl(txtRetained.Text) Then
            '            If MsgBox("Annual premium (" & FormatCurrency(dsRibs.Tables("Ribs").Rows(0).Item("NEW_PREMIUM_AMOUNT")) & ")" & _
            '                        " not equal to retained premium (" & FormatCurrency(CDbl(txtRetained.Text)) & ")" & _
            '                        " Would you like to replace retained premium?", MsgBoxStyle.YesNo, "Replace") = MsgBoxResult.Yes Then
            '                txtRetained.Text = FormatCurrency(dsRibs.Tables("Ribs").Rows(0).Item("NEW_PREMIUM_AMOUNT"))
            '            End If
            '        End If
            '    End If
            'End If

            'dtlDate.Enabled = True
            'comAction.Enabled = True
            'txtNote.Enabled = True
            'txtRetained.Enabled = True
            'txtWriteoff.Enabled = True
            'comContactMethod.Enabled = True

        Catch ex As Exception
            DisplayErrors(ex)
        End Try

    End Sub

    Sub Import()
        Try
            Cursor = Cursors.WaitCursor
            Dim lFile As String
            Dim lFiles() As String
            Dim dt As DataTable
            Dim oDataImport As New RibsDataImportClass
            Dim oBrows As New OpenFileDialog
            oBrows.Title = "Select Import File"
            oBrows.Filter = "Excel (*.xls)|*.xls|All (*.*)|*.*"
            oBrows.InitialDirectory = My.Settings.ImportDataFolder
            oBrows.Multiselect = True
            oBrows.ShowDialog()
            lFiles = oBrows.FileNames

            If oBrows.FileName <> "" Then
                My.Settings.ImportDataFolder = oBrows.FileName
                My.Settings.Save()
                For Each lFile In lFiles
                    If IsTextFile(lFile, "_RECORD_ID") Then
                        dt = LoadTextFile(lFile)
                    Else
                        dt = ImportExcel(lFile)
                    End If

                    dt = oDataImport.DataImport(dt)
                    If dt.Rows.Count > 0 Then
                        Dim f As New frmImportError
                        f.dgErrors.DataSource = dt
                        f.dgErrors.Columns("Import Status").DisplayIndex = 0
                        f.dgErrors.Columns("Import Status").Width = 200
                        f.dgErrors.Columns("_RECORD_ID").Visible = False
                        f.Text = dt.Rows.Count & " Row/s found in .." & Microsoft.VisualBasic.Right(lFile, 50)
                        f.ShowDialog()
                    Else
                        MsgBox("Successfully imported Data", MsgBoxStyle.Information, "Import")
                    End If
                Next
            Else
                Beep()
            End If

        Catch ex As Exception
            DisplayErrors(ex)
        End Try
        Cursor = Cursors.Default
    End Sub

#Region " Screen Handlers "

    Private Sub LoadRipsList(Optional ByVal Search As String = "")
        Try
            Cursor = Cursors.WaitCursor
            ToggleScreenButtonsState(ScreenState.Loading)
            'dgFullList.Enabled = False
            Application.DoEvents()
            Dim oRibs As New RibsClass
            Dim iCol As DataGridViewColumn
            Dim ds As DataSet = oRibs.GetRibsList(Search, RibsClass.ReturnType.Main, comData.Text)

            dgFullList.DataSource = FilterRIBS(ds, ReturnType.Main)
            dgFullList.DataMember = "Ribs"
            For Each iCol In dgFullList.Columns
                iCol.Visible = False
            Next
            If dgFullList.Columns.Count > 0 Then

                dgFullList.Columns("RECORD_ID").HeaderText = "Record ID"
                dgFullList.Columns("RECORD_ID").Visible = True
                'dgFullList.Columns("RECORD_ID").DisplayIndex = 1

                dgFullList.Columns("RibsState").HeaderText = "Status"
                dgFullList.Columns("RibsState").Visible = True
                'dgFullList.Columns("Description").DisplayIndex = 2

                dgFullList.Columns("Action").HeaderText = "Last Action"
                dgFullList.Columns("Action").Visible = True

                dgFullList.Columns("Letter_Code").HeaderText = "Letter Code"
                dgFullList.Columns("Letter_Code").Visible = True

                dgFullList.Columns("ActionDate").HeaderText = "Action Date"
                dgFullList.Columns("ActionDate").Visible = True
                dgFullList.Columns("ActionDate").DefaultCellStyle.Format = "dd-MMM-yy"
                'dgFullList.Columns("ActionDate").DisplayIndex = 3

                dgFullList.Columns("AMOUNT_Due").HeaderText = "Amount Due"
                dgFullList.Columns("AMOUNT_Due").Visible = True
                dgFullList.Columns("AMOUNT_Due").DefaultCellStyle.Format = "c"
                dgFullList.Columns("AMOUNT_Due").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                dgFullList.Columns("Policy_Number").HeaderText = "Policy Number"
                dgFullList.Columns("Policy_Number").Visible = True

                dgFullList.Columns("Product_Type").HeaderText = "Product Type"
                dgFullList.Columns("Product_Type").Visible = True

                dgFullList.Columns("Mailing_Name").HeaderText = "Client Name"
                dgFullList.Columns("Mailing_Name").Visible = True

                dgFullList.Columns("MAILING_ADDRESS_1").HeaderText = "Mail Address"
                dgFullList.Columns("MAILING_ADDRESS_1").Visible = True

                dgFullList.Columns("MAILING_ADDRESS_2").HeaderText = "Mail Address"
                dgFullList.Columns("MAILING_ADDRESS_2").Visible = True

                dgFullList.Columns("PRODUCT_TYPE").HeaderText = "Product Type"
                dgFullList.Columns("PRODUCT_TYPE").Visible = True

                dgFullList.Columns("MAILING_STATE").HeaderText = "Mailing State"
                dgFullList.Columns("MAILING_STATE").Visible = True

                dgFullList.Columns("ADVISOR_FORENAME").HeaderText = "Adviser Forename"
                dgFullList.Columns("ADVISOR_FORENAME").Visible = True

                dgFullList.Columns("ADVISER_SURNAME").HeaderText = "Adviser Surname"
                dgFullList.Columns("ADVISER_SURNAME").Visible = True

                dgFullList.Columns("ADVISER_AGENT_NUMBER").HeaderText = "Advise Number"
                dgFullList.Columns("ADVISER_AGENT_NUMBER").Visible = True

                dgFullList.Columns("ADVISER_PHONE_NUMBER").HeaderText = "Adv Phone"
                dgFullList.Columns("ADVISER_PHONE_NUMBER").Visible = True

                dgFullList.Columns("Account_SYSTEM").HeaderText = "System"
                dgFullList.Columns("Account_SYSTEM").Visible = True

                dgFullList.Columns("DUE_DATE").HeaderText = "Due Date"
                dgFullList.Columns("DUE_DATE").Visible = True
                dgFullList.Columns("DUE_DATE").DefaultCellStyle.Format = "dd-MMM-yy"

                dgFullList.Columns("LETTER_DATE").HeaderText = "Letter Date"
                dgFullList.Columns("LETTER_DATE").Visible = True
                dgFullList.Columns("LETTER_DATE").DefaultCellStyle.Format = "dd-MMM-yy"

                dgFullList.Columns("NEW_PREMIUM_AMOUNT").HeaderText = "Annual premium"
                dgFullList.Columns("NEW_PREMIUM_AMOUNT").Visible = True
                dgFullList.Columns("NEW_PREMIUM_AMOUNT").DefaultCellStyle.Format = "c"
                dgFullList.Columns("NEW_PREMIUM_AMOUNT").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                dgFullList.Columns("UserID").HeaderText = "User"
                dgFullList.Columns("UserID").Visible = True
                Dim Sortcol As DataGridViewColumn = dgFullList.Columns("ActionDate")
                dgFullList.Sort(Sortcol, System.ComponentModel.ListSortDirection.Descending)
            End If
            dgFullList.RowHeadersWidth = 10
            ToggleScreenButtonsState(ScreenState.Loading)
            Try
                If My.Settings.FullListColWidth <> "" Then
                    Dim col As DataGridViewColumn
                    Dim sCols() As String = Split(My.Settings.FullListColWidth, ",")
                    For Each col In dgFullList.Columns
                        If col.Index < sCols.GetUpperBound(0) Then
                            col.Width = CInt(sCols(col.Index))
                        End If
                    Next
                End If
                If My.Settings.FullListColumnDisplayIndex <> "" Then
                    Dim colName As String
                    Dim col As DataGridViewColumn
                    Dim sCols() As String = Split(My.Settings.FullListColumnDisplayIndex, ",")
                    For Each colName In sCols
                        If Trim(colName) <> "" Then
                            col = dgFullList.Columns(Split(colName, "|")(0))
                            col.DisplayIndex = Split(colName, "|")(1)
                        End If
                    Next
                End If
            Catch ex As Exception
            End Try

            ClearRibsDetailScreen()
            LoadRipsTaskList()
            tbSaveSettings.Enabled = False
            ToggleScreenButtonsState(ScreenState.ViewData)
        Catch ex As Exception
            ToggleScreenButtonsState(ScreenState.ViewData)
            DisplayErrors(ex)
        End Try
        Cursor = Cursors.Default
    End Sub

    Sub SaveColumnWidths()
        Try
            Dim col As DataGridViewColumn
            Dim sCols As String = ""
            For Each col In dgFullList.Columns
                sCols += col.Width & ","
            Next
            My.Settings.FullListColWidth = sCols
            My.Settings.Save()

            sCols = ""
            For Each col In dgTasks.Columns
                sCols += col.Width & ","
            Next
            My.Settings.TasksFullListColWidth = sCols
            My.Settings.Save()

            sCols = ""
            For Each col In dgHistory.Columns
                sCols += col.Width & ","
            Next
            My.Settings.HistoryFullListColWidth = sCols
            My.Settings.Save()
        Catch ex As Exception

        End Try
    End Sub

    Sub SaveColumnDisplayIndex()
        Try
            Dim col As DataGridViewColumn
            Dim sCols As String = ""
            For Each col In dgFullList.Columns
                sCols += col.Name & "|" & col.DisplayIndex & ","
            Next
            My.Settings.FullListColumnDisplayIndex = sCols
            My.Settings.Save()

            sCols = ""
            For Each col In dgTasks.Columns
                sCols += col.Name & "|" & col.DisplayIndex & ","
            Next
            My.Settings.TasksFullListColumnDisplayIndex = sCols
            My.Settings.Save()

            sCols = ""
            For Each col In dgHistory.Columns
                sCols += col.Name & "|" & col.DisplayIndex & ","
            Next
            My.Settings.HistoryFullListColumnDisplayIndex = sCols
            My.Settings.Save()

        Catch ex As Exception

        End Try
    End Sub

    Private Sub dgTasks_ColumnDisplayIndexChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles dgTasks.ColumnDisplayIndexChanged
        tbSaveSettings.Enabled = True
    End Sub

    Private Sub dgTasks_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles dgTasks.ColumnWidthChanged
        tbSaveSettings.Enabled = True
    End Sub

    Private Sub dgHistory_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles dgHistory.ColumnWidthChanged
        tbSaveSettings.Enabled = True
    End Sub
    Private Sub dgHistory_ColumnDisplayIndexChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles dgHistory.ColumnDisplayIndexChanged
        tbSaveSettings.Enabled = True
    End Sub

    Private Sub dgFullList_ColumnDisplayIndexChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles dgFullList.ColumnDisplayIndexChanged
        tbSaveSettings.Enabled = True
    End Sub
    Private Sub dgFullList_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles dgFullList.ColumnWidthChanged
        tbSaveSettings.Enabled = True
    End Sub

    Private Sub LoadRipsTaskList()
        Try
            'Dim i As Int32 = 1
            'i = i / 0
            Cursor = Cursors.WaitCursor
            Application.DoEvents()
            Dim oRibs As New RibsClass
            Dim iCol As DataGridViewColumn
            Dim ds As DataSet = oRibs.GetRibsList("", RibsClass.ReturnType.Tasks)
            dgTasks.DataSource = FilterRIBS(ds, ReturnType.Tasks)
            dgTasks.DataMember = "Ribs"
            For Each iCol In dgTasks.Columns
                iCol.Visible = False
            Next
            If dgTasks.Columns.Count > 0 Then
                dgTasks.Columns("ActionDate").HeaderText = "Action Date"
                dgTasks.Columns("ActionDate").Visible = True
                dgTasks.Columns("ActionDate").DefaultCellStyle.Format = "dd-MMM-yy"
                dgTasks.Columns("ActionDate").DisplayIndex = 0

                dgTasks.Columns("Action").HeaderText = "Next Action"
                dgTasks.Columns("Action").Visible = True

                dgTasks.Columns("RibsState").HeaderText = "Status"
                dgTasks.Columns("RibsState").Visible = True
                'dgTasks.Columns("RibsState").DisplayIndex = 2

                dgTasks.Columns("Letter_Code").HeaderText = "Letter Code"
                dgTasks.Columns("Letter_Code").Visible = True

                'dgTasks.Columns("Description").HeaderText = "Description"
                'dgTasks.Columns("Description").Visible = True
                'dgTasks.Columns("Description").DisplayIndex = 1

                dgTasks.Columns("AMOUNT_Due").HeaderText = "Amount Due"
                dgTasks.Columns("AMOUNT_Due").Visible = True
                dgTasks.Columns("AMOUNT_Due").DefaultCellStyle.Format = "c"
                dgTasks.Columns("AMOUNT_Due").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                dgTasks.Columns("Policy_Number").HeaderText = "Policy Number"
                dgTasks.Columns("Policy_Number").Visible = True

                dgTasks.Columns("Product_Type").HeaderText = "Product Type"
                dgTasks.Columns("Product_Type").Visible = True

                dgTasks.Columns("Mailing_Name").HeaderText = "Client Name"
                dgTasks.Columns("Mailing_Name").Visible = True

                'dgTasks.Columns("MAILING_ADDRESS_1").HeaderText = "Mail Address"
                'dgTasks.Columns("MAILING_ADDRESS_1").Visible = True

                'dgTasks.Columns("MAILING_ADDRESS_2").HeaderText = "Mail Address"
                'dgTasks.Columns("MAILING_ADDRESS_2").Visible = True

                dgTasks.Columns("PRODUCT_TYPE").HeaderText = "Product Type"
                dgTasks.Columns("PRODUCT_TYPE").Visible = True

                'dgTasks.Columns("MAILING_NAME").HeaderText = "Mailin Name"
                'dgTasks.Columns("MAILING_NAME").Visible = True

                'dgTasks.Columns("MAILING_STATE").HeaderText = "Mailing State"
                'dgTasks.Columns("MAILING_STATE").Visible = True

                'dgTasks.Columns("ADVISOR_FORENAME").HeaderText = "Adviser Forename"
                'dgTasks.Columns("ADVISOR_FORENAME").Visible = True

                dgTasks.Columns("ADVISER_SURNAME").HeaderText = "Adviser Surname"
                dgTasks.Columns("ADVISER_SURNAME").Visible = True

                'dgTasks.Columns("ADVISER_AGENT_NUMBER").HeaderText = "Advise Number"
                'dgTasks.Columns("ADVISER_AGENT_NUMBER").Visible = True

                'dgTasks.Columns("ADVISER_PHONE_NUMBER").HeaderText = "Adv Phone"
                'dgTasks.Columns("ADVISER_PHONE_NUMBER").Visible = True

                'dgTasks.Columns("DUE_DATE").HeaderText = "Due Date"
                'dgTasks.Columns("DUE_DATE").Visible = True
                'dgTasks.Columns("DUE_DATE").DefaultCellStyle.Format = "dd-MMM-yy"

                'dgTasks.Columns("LETTER_DATE").HeaderText = "Letter Date"
                'dgTasks.Columns("LETTER_DATE").Visible = True
                'dgTasks.Columns("LETTER_DATE").DefaultCellStyle.Format = "dd-MMM-yy"


                'dgTasks.Columns("NEW_PREMIUM_AMOUNT").HeaderText = "New Premium"
                'dgTasks.Columns("NEW_PREMIUM_AMOUNT").Visible = True
                'dgTasks.Columns("NEW_PREMIUM_AMOUNT").DefaultCellStyle.Format = "c"
                'dgTasks.Columns("NEW_PREMIUM_AMOUNT").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                dgTasks.RowHeadersWidth = 10
            End If
            Try
                If My.Settings.TasksFullListColWidth <> "" Then
                    ToggleScreenButtonsState(ScreenState.Loading)
                    Dim col As DataGridViewColumn
                    Dim sCols() As String = Split(My.Settings.TasksFullListColWidth, ",")
                    For Each col In dgTasks.Columns
                        If col.Index < sCols.GetUpperBound(0) Then
                            col.Width = CInt(sCols(col.Index))
                        End If
                    Next
                End If
                If My.Settings.TasksFullListColumnDisplayIndex <> "" Then
                    ToggleScreenButtonsState(ScreenState.Loading)
                    Dim colName As String
                    Dim col As DataGridViewColumn
                    Dim sCols() As String = Split(My.Settings.TasksFullListColumnDisplayIndex, ",")
                    For Each colName In sCols
                        If Trim(colName) <> "" Then
                            col = dgTasks.Columns(Split(colName, "|")(0))
                            col.DisplayIndex = Split(colName, "|")(1)
                        End If
                    Next
                End If
            Catch ex As Exception

            End Try

            ToggleScreenButtonsState(ScreenState.ViewData)
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
        Cursor = Cursors.Default
    End Sub

    Sub SelectTaskListHistoryItem()
        Try
            Dim oRibs As New RibsClass
            Try
                CurrentID = dgTasks.SelectedRows(0).Cells("RibsID").Value
            Catch ex As Exception
            End Try
            If CurrentID = 0 Then
                Beep()
            Else
                ToggleScreenButtonsState(ScreenState.CanAddRecordAndEditRecord)
                dsRibs = oRibs.GetRibsItem(CurrentID, comData.Text)
                BindRibsData()
            End If
            dgTasks.Focus()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Sub SelectTaskListItem()
        Try
            Dim oRibs As New RibsClass
            Try
                CurrentID = dgTasks.SelectedRows(0).Cells("RibsID").Value
            Catch ex As Exception
            End Try
            If CurrentID = 0 Then
                Beep()
            Else
                ToggleScreenButtonsState(ScreenState.CanAddRecordAndEditRecord)
                dsRibs = oRibs.GetRibsItem(CurrentID, comData.Text)
                BindRibsData()
            End If
            dgTasks.Focus()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Private Sub dgTasks_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgTasks.KeyUp
        Try
            SelectTaskListItem()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Private Sub dgTasks_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgTasks.MouseUp
        Try
            SelectTaskListItem()
            '  GetHistory()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Sub GetHistory(ByVal RibsID As Int32, ByVal POLICY_NUMBER As String)
        Try
            Dim ds As DataSet
            Dim oRibs As New RibsClass
            Dim oSetting As New SystemSetting
            Dim DisplayHistoryColoums As String = oSetting.HistoryColumns.ToUpper
            bSaveGridSetting = False
            gdHist.Enabled = False

            ds = oRibs.GetRibsItemHistory(RibsID, POLICY_NUMBER)
            gdHist.DataSource = ds.Tables("Ribs")

            Try
                gdHist.SelectionMode = DataGridViewSelectionMode.FullRowSelect

                'For Each col As DataGridViewColumn In gdHist.Columns
                '    col.Visible = False
                'Next

                If gdHist.Columns.Count > 0 Then

                    gdHist.Columns("RECORD_ID").HeaderText = "Record ID"
                    gdHist.Columns("RECORD_ID").Visible = True

                    'gdHist.Columns("RibsState").HeaderText = "Status"
                    'gdHist.Columns("RibsState").Visible = True

                    ' gdHist.Columns("Action").HeaderText = "Last Action"
                    'gdHist.Columns("Action").Visible = True

                    gdHist.Columns("Letter_Code").HeaderText = "Letter Code"
                    gdHist.Columns("Letter_Code").Visible = True

                    'gdHist.Columns("ActionDate").HeaderText = "Action Date"
                    'gdHist.Columns("ActionDate").Visible = True
                    'gdHist.Columns("ActionDate").DefaultCellStyle.Format = "dd-MMM-yy"

                    gdHist.Columns("AMOUNT_Due").HeaderText = "Amount Due"
                    gdHist.Columns("AMOUNT_Due").Visible = True
                    gdHist.Columns("AMOUNT_Due").DefaultCellStyle.Format = "c"
                    gdHist.Columns("AMOUNT_Due").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                    gdHist.Columns("Policy_Number").HeaderText = "Policy Number"
                    gdHist.Columns("Policy_Number").Visible = True

                    gdHist.Columns("Product_Type").HeaderText = "Product Type"
                    gdHist.Columns("Product_Type").Visible = True

                    gdHist.Columns("Mailing_Name").HeaderText = "Client Name"
                    gdHist.Columns("Mailing_Name").Visible = True

                    gdHist.Columns("MAILING_ADDRESS_1").HeaderText = "Mail Address"
                    gdHist.Columns("MAILING_ADDRESS_1").Visible = True

                    gdHist.Columns("MAILING_ADDRESS_2").HeaderText = "Mail Address"
                    gdHist.Columns("MAILING_ADDRESS_2").Visible = True

                    gdHist.Columns("PRODUCT_TYPE").HeaderText = "Product Type"
                    gdHist.Columns("PRODUCT_TYPE").Visible = True

                    gdHist.Columns("MAILING_STATE").HeaderText = "Mailing State"
                    gdHist.Columns("MAILING_STATE").Visible = True

                    gdHist.Columns("ADVISOR_FORENAME").HeaderText = "Adviser Forename"
                    gdHist.Columns("ADVISOR_FORENAME").Visible = True

                    gdHist.Columns("ADVISER_SURNAME").HeaderText = "Adviser Surname"
                    gdHist.Columns("ADVISER_SURNAME").Visible = True

                    gdHist.Columns("ADVISER_AGENT_NUMBER").HeaderText = "Advise Number"
                    gdHist.Columns("ADVISER_AGENT_NUMBER").Visible = True

                    gdHist.Columns("ADVISER_PHONE_NUMBER").HeaderText = "Adv Phone"
                    gdHist.Columns("ADVISER_PHONE_NUMBER").Visible = True

                    gdHist.Columns("Account_SYSTEM").HeaderText = "System"
                    gdHist.Columns("Account_SYSTEM").Visible = True

                    gdHist.Columns("DUE_DATE").HeaderText = "Due Date"
                    gdHist.Columns("DUE_DATE").Visible = True
                    gdHist.Columns("DUE_DATE").DefaultCellStyle.Format = "dd-MMM-yy"

                    gdHist.Columns("LETTER_DATE").HeaderText = "Letter Date"
                    gdHist.Columns("LETTER_DATE").Visible = True
                    gdHist.Columns("LETTER_DATE").DefaultCellStyle.Format = "dd-MMM-yy"

                    gdHist.Columns("NEW_PREMIUM_AMOUNT").HeaderText = "Annual premium"
                    gdHist.Columns("NEW_PREMIUM_AMOUNT").Visible = True
                    gdHist.Columns("NEW_PREMIUM_AMOUNT").DefaultCellStyle.Format = "c"
                    gdHist.Columns("NEW_PREMIUM_AMOUNT").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                    gdHist.Columns("UserID").HeaderText = "User"
                    gdHist.Columns("UserID").Visible = True

                    For Each col As DataGridViewColumn In gdHist.Columns
                        If DisplayHistoryColoums.Contains(col.Name.ToUpper) Then
                            col.Visible = True
                        Else
                            col.Visible = False
                        End If
                    Next
                    gdHist.Enabled = True

                    For Each str As String In oSetting.HistoryColumns_Settings.Trim.ToUpper.Split("|")
                        Try
                            'For Each ColDtl As String In str.ToUpper.Split("|")
                            Dim Col As String = str.Split(";")(0)
                            If DisplayHistoryColoums.Contains(Col) Then
                                Try
                                    gdHist.Columns(Col).DisplayIndex = str.Split(";")(1)
                                    gdHist.Columns(Col).Width = str.Split(";")(2)
                                Catch ex As Exception
                                    Debug.Print(ex.Message)
                                End Try
                            End If
                            'Next

                        Catch ex As Exception

                        End Try

                    Next

                End If
                bSaveGridSetting = True
            Catch ex As Exception

            End Try
        Catch ex As Exception
            Beep()
        End Try

    End Sub

    Sub SaveGridSetting()
        If bSaveGridSetting Then
            Dim sData As String = ""
            Dim oSetting As New SystemSetting
            For Each col As DataGridViewColumn In gdHist.Columns
                'Debug.Print(col.DisplayIndex)
                'Debug.Print(col.Name)
                'Debug.Print(col.DisplayIndex)
                sData &= col.Name & ";" & col.DisplayIndex & ";" & col.Width & "|"
            Next
            oSetting.HistoryColumns_Settings = sData
        End If

    End Sub

    Sub ChangeCurrentItem()
        Try
            Dim oRibs As New RibsClass
            Dim POLICY_NUMBER As String = ""
            Try
                CurrentID = dgFullList.SelectedRows(0).Cells("RibsID").Value
                POLICY_NUMBER = dgFullList.SelectedRows(0).Cells("POLICY_NUMBER").Value
            Catch ex As Exception
            End Try
            If CurrentID = 0 Then
                Beep()
            Else
                ToggleScreenButtonsState(ScreenState.CanAddRecord)
                dsRibs = oRibs.GetRibsItem(CurrentID, comData.Text)
                BindRibsData()
                GetHistory(CurrentID, POLICY_NUMBER)
            End If

        Catch ex As Exception
            ' DisplayErrors(ex)
        End Try
    End Sub

    Private Sub dgFullList_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgFullList.MouseUp
        ChangeCurrentItem()
        dgFullList.Focus()
    End Sub

    Sub BindRibsData()
        Try
            ClearRibsData()
            bmRibs = Me.BindingContext(dsRibs, "Ribs")

            comNoticeCode.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.LETTER_CODE"))
            txtSystem.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.Account_SYSTEM"))
            txtAmountDue.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.Amount_Due"))
            txtPolicyNumber.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.POLICY_NUMBER"))

            txtProductType.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.PRODUCT_TYPE"))
            txtMailingName.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.MAILING_NAME"))

            txtMailingAddress1.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.MAILING_ADDRESS_1"))
            txtMailingAddress2.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.MAILING_ADDRESS_2"))
            txtMailingAddress3.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.MAILING_ADDRESS_3"))
            txtMailingAddress4.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.MAILING_SUBURB"))
            txtMailingAddress5.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.MAILING_STATE"))
            txtMailingAddress6.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.MAILING_POSTCODE"))

            txtAdviserName.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.ADVISER_SURNAME"))
            'txtAdviserName.Text = LTrim(dsRibs.Tables("Ribs").Rows(0).Item("ADVISOR_FORENAME") & " " & dsRibs.Tables("Ribs").Rows(0).Item("ADVISER_SURNAME"))
            'txtMailingAddress.Text = dsRibs.Tables("Ribs").Rows(0).Item("MAILING_ADDRESS_1") & vbCrLf
            'txtMailingAddress.Text = dsRibs.Tables("Ribs").Rows(0).Item("MAILING_ADDRESS_2") & vbCrLf
            'txtMailingAddress.Text = dsRibs.Tables("Ribs").Rows(0).Item("MAILING_ADDRESS_3") & vbCrLf
            'txtMailingAddress.Text = dsRibs.Tables("Ribs").Rows(0).Item("MAILING_SUBURB") & vbCrLf
            'txtMailingAddress.Text = dsRibs.Tables("Ribs").Rows(0).Item("MAILING_STATE") & vbCrLf
            'txtMailingAddress.Text += dsRibs.Tables("Ribs").Rows(0).Item("MAILING_STATE") & vbCrLf
            'txtMailingAddress.Text += dsRibs.Tables("Ribs").Rows(0).Item("MAILING_POSTCODE") & vbCrLf

            txtAdviserNumber.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.ADVISER_AGENT_NUMBER"))
            txtAdviserEmail.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.ADVISER_EMAIL_ADDRESS"))
            txtAdviserPhone.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.ADVISER_PHONE_NUMBER"))

            tpLetterDate.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.LETTER_DATE"))
            dpDueDate.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.DUE_DATE"))
            txtNewAmount.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.NEW_PREMIUM_AMOUNT"))
            txtSuperInd.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.SUPERANNUATION_INDICATOR"))
            txtPaymentFreq.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.PAYMENT_FREQUENCY"))

            'comUser.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.UserID"))
            txtRetained.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.Retained"))
            txtRetained.Text = FormatCurrency(txtRetained.Text, 2)
            txtWriteoff.DataBindings.Add(New Binding("Text", dsRibs, "Ribs.Writeoff"))
            txtWriteoff.Text = FormatCurrency(txtWriteoff.Text, 2)

            LoadHistoryGrid(dsRibs.Tables("ActionHistory"))

        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Sub LoadHistoryGrid(ByVal dt As DataTable)
        Try
            ToggleScreenButtonsState(ScreenState.Loading)
            If dt.Rows.Count > 0 Then
                txtNote.Text = dt.Rows(0).Item("Note")
                comAction.Text = dt.Rows(0).Item("Action")
                comStatus.Text = dt.Rows(0).Item("RibsState")
                comContactMethod.Text = dt.Rows(0).Item("ContactMethod")
                dtlDate.Text = dt.Rows(0).Item("ActionDate")
                lblReason.Visible = False

                If Not IsDBNull(dt.Rows(0).Item("Reason")) Then
                    If Len(Trim(dt.Rows(0).Item("Reason"))) > 0 Then
                        lblReason.Visible = True
                        lblReason.Text = dt.Rows(0).Item("Reason")
                    End If
                End If

            End If
            dgHistory.DataSource = dt
            dgHistory.SelectionMode = DataGridViewSelectionMode.FullRowSelect
            dgHistory.Columns("ActionID").Visible = False
            dgHistory.Columns("RibsID").Visible = False

            dgHistory.Columns("ActionDate").HeaderText = "Action Date"
            dgHistory.Columns("ActionDate").DefaultCellStyle.Format = "dd-MMM-yy"
            dgHistory.Columns("ActionDate").DisplayIndex = 0

            dgHistory.Columns("Action").HeaderText = "Action"
            dgHistory.Columns("Action").DisplayIndex = 1

            dgHistory.Columns("ContactMethod").HeaderText = "Contact Method"
            dgHistory.Columns("ContactMethod").DisplayIndex = 2

            dgHistory.Columns("Note").HeaderText = "Note"
            dgHistory.Columns("Note").DisplayIndex = 3

            dgHistory.Columns("User").HeaderText = "User"
            dgHistory.Columns("User").DisplayIndex = 4

            dgHistory.Columns("EntryDate").HeaderText = "Entry Date"
            dgHistory.Columns("EntryDate").DefaultCellStyle.Format = "dd-MMM-yy"
            dgHistory.Columns("EntryDate").DisplayIndex = 6

            'dgHistory.Columns("NEW_PREMIUM_AMOUNT").HeaderText = "Annual premium"

            dgHistory.Columns("RibsState").HeaderText = "Status"
            dgHistory.Columns("RibsState").DisplayIndex = 7
            Dim SortCol As DataGridViewColumn = dgHistory.Columns("EntryDate")
            dgHistory.Sort(SortCol, System.ComponentModel.ListSortDirection.Descending)
            Try
                If My.Settings.HistoryFullListColWidth <> "" Then
                    Dim col As DataGridViewColumn
                    Dim sCols() As String = Split(My.Settings.HistoryFullListColWidth, ",")
                    For Each col In dgHistory.Columns
                        If col.Index < sCols.GetUpperBound(0) Then
                            col.Width = CInt(sCols(col.Index))
                        End If
                    Next
                End If
                If My.Settings.HistoryFullListColumnDisplayIndex <> "" Then
                    Dim colName As String
                    Dim col As DataGridViewColumn
                    Dim sCols() As String = Split(My.Settings.HistoryFullListColumnDisplayIndex, ",")
                    For Each colName In sCols
                        If Trim(colName) <> "" Then
                            col = dgHistory.Columns(Split(colName, "|")(0))
                            col.DisplayIndex = Split(colName, "|")(1)
                        End If
                    Next
                End If
            Catch ex As Exception

            End Try

            dgHistory.Enabled = True
            ToggleScreenButtonsState(ScreenState.ViewData)
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Sub ClearRibsDetailScreen()
        Try
            For Each ct As Control In tabContact.Controls
                ct.DataBindings.Clear()
                If ct.GetType.ToString <> GetType(Label).ToString Then
                    ct.Text = ""
                End If
            Next
            For Each ct As Control In tabStripData.Controls
                ct.DataBindings.Clear()
                If ct.GetType.ToString <> GetType(Label).ToString Then
                    ct.Text = ""
                End If
            Next
            dgHistory.DataSource = Nothing
            lblPolicyNumber.Text = ""
            lblMailingName.Text = ""
            comAction.Text = ""
            comStatus.Text = ""
            comContactMethod.Text = ""
            txtNote.Text = ""
            tabContact.Text = "Contact"
            tabDetail.Text = "Detail"

        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Sub ClearRibsData()

        comNoticeCode.DataBindings.Clear()
        txtSystem.DataBindings.Clear()
        txtAmountDue.DataBindings.Clear()
        txtPolicyNumber.DataBindings.Clear()

        txtProductType.DataBindings.Clear()
        txtMailingName.DataBindings.Clear()

        txtMailingAddress1.DataBindings.Clear()
        txtMailingAddress2.DataBindings.Clear()
        txtMailingAddress3.DataBindings.Clear()
        txtMailingAddress4.DataBindings.Clear()
        txtMailingAddress5.DataBindings.Clear()
        txtMailingAddress6.DataBindings.Clear()

        txtAdviserName.DataBindings.Clear()
        txtAdviserNumber.DataBindings.Clear()
        txtAdviserNumber.DataBindings.Clear()
        txtAdviserEmail.DataBindings.Clear()
        txtAdviserPhone.DataBindings.Clear()

        tpLetterDate.DataBindings.Clear()
        dpDueDate.DataBindings.Clear()
        txtNewAmount.DataBindings.Clear()
        txtSuperInd.DataBindings.Clear()
        txtPaymentFreq.DataBindings.Clear()

        'comUser.DataBindings.Clear()
        txtRetained.DataBindings.Clear()
        txtWriteoff.DataBindings.Clear()

    End Sub

    Private Sub txtDueDate_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        sender.text = FormatDateTime(sender.Text, DateFormat.ShortDate)
    End Sub

    Private Sub txtLetterDate_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        sender.text = FormatDateTime(sender.Text, DateFormat.ShortDate)
    End Sub

#End Region

#Region "Tool & Menu Bar Functions "

    Private Sub MyFilter()
        Try
            Text = MainCaption '& " <My Filter>"
            SystemFilter = False
            MyFilterToolStripButton.Enabled = False
            SystemFilterToolStripButton.Enabled = True
            LoadRipsList()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub MyFilterToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyFilterToolStripButton.Click
        MyFilter()

    End Sub
    Private Sub mnuMyFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuMyFilter.Click
        MyFilter()
    End Sub

    Private Sub aSystemFilter()
        Try
            Text = MainCaption '& " <System Filter>"
            SystemFilter = True
            MyFilterToolStripButton.Enabled = True
            SystemFilterToolStripButton.Enabled = False
            LoadRipsList()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub mnuSystemFilter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSystemFilter.Click
        aSystemFilter()
    End Sub
    Private Sub SystemFilterToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SystemFilterToolStripButton.Click
        aSystemFilter()
    End Sub

    Private Sub SaveMySettings()
        Try
            SaveColumnWidths()
            SaveColumnDisplayIndex()
            tbSaveSettings.Enabled = False
        Catch ex As Exception
            tbSaveSettings.Enabled = False
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub mnuSaveMySettingsTo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSaveMySettingsTo.Click
        SaveMySettings()
    End Sub
    Private Sub ToolbarSaveSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbSaveSettings.Click
        SaveMySettings()
    End Sub

    Private Sub mnuOepnServiceRequest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuOepnServiceRequest.Click
        Try
            RaiseQuestion()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub toolbarQuestion_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles toolbarQuestion.Click
        Try
            RaiseQuestion()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Private Sub ImportData()
        Try
            If oSec.CheckUserSecurity(NetWorkUserID, RIBS.UserSecurity.RIBSSecurityAction.EnterWorkLoadScreen) Then
                DisableScreen()
                ToolStripProgressBar1.Maximum = 5

                ToolStripProgressBar1.Visible = True
                Application.DoEvents()
                ToolStripProgressBar1.Value = 2
                Import()
                EnableScreen()
                ToolStripProgressBar1.Value = ToolStripProgressBar1.Maximum
                ToolStripProgressBar1.Visible = False
            Else
                SecurityMessage()
            End If
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
        Cursor = Cursors.Default
    End Sub
    Private Sub mnuImportData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuImportData.Click
        ImportData()
    End Sub
    Private Sub ImportStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportStripButton.Click
        ImportData()
    End Sub

    Private Sub EditCurrentHistory()

        ToggleScreenButtonsState(ScreenState.EditingRecord)

        bEditingCurrent = True

        ToggleTabDetail(True)

        LoadDropDownBoxes()

        CopyHistoryGridtoScreen()
    End Sub

    Private Sub AddHistoryRec()
        Try
            If oSec.CheckUserSecurity(NetWorkUserID, RIBS.UserSecurity.RIBSSecurityAction.AddHistory) Then
                ToggleScreenButtonsState(ScreenState.AddingRecord)

                AddRec()
            Else
                SecurityMessage()
            End If

        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub mnuEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAddRecord.Click
        AddHistoryRec()
    End Sub
    Private Sub EditToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbAddHistoryRecord.Click
        AddHistoryRec()
    End Sub

    Private Sub Save()
        Try
            Dim oRibs As New RibsClass
            Dim Reason As String = ""
            ToggleScreenButtonsState(ScreenState.ViewData)

            bmRibs.EndCurrentEdit()
TryAgain:
            If oRibs.CheckReason(comStatus.Text) Then
                Dim oFrm As New frmReason
                oFrm.Text = "Provide reason for '" & comStatus.Text & "' status"
                oFrm.ShowDialog()
                If oFrm.DialogResult = Windows.Forms.DialogResult.OK Then
                    If oFrm.comReason.Text.Length = 0 Then
                        MsgBox("Provide reason for '" & comStatus.Text & "' status", MsgBoxStyle.Exclamation, "Error")
                        GoTo TryAgain
                    Else
                        Reason = oFrm.comReason.Text
                    End If
                Else
                    MsgBox("Provide reason for '" & comStatus.Text & "' status", MsgBoxStyle.Exclamation, "Error")
                    GoTo DONOTHING
                End If
            End If
            ToggleScreenButtonsState(ScreenState.ViewData)

            ToggleTabDetail(False)
            ToggleTabContact(False)

            If dsRibs.HasChanges Then
                dsRibs.Tables("Ribs").Rows(0).Item("UserID") = tbComBoUsers.Text.ToUpper
                oRibs.Save(dsRibs.GetChanges, CurrentID)
            End If

            If Trim(comAction.Text) <> "" And Trim(txtNote.Text) <> "" And comStatus.Text <> "" Then
                If bEditingCurrent Then
                    If oRibs.UpDateAction(CurrentActionID, comAction.Text, txtNote.Text, dtlDate.Value, comContactMethod.Text, comStatus.Text, Reason, NetWorkUserID) Then
                        bEditingCurrent = False
                        Application.DoEvents()
                        LoadHistoryGrid(oRibs.GetActionHistory(CurrentID))
                        comAction.Text = ""
                        txtNote.Text = ""
                        Application.DoEvents()
                    End If
                Else
                    If oRibs.InsertNewAction(CurrentID, comAction.Text, txtNote.Text, dtlDate.Value, comContactMethod.Text, comStatus.Text, Reason, NetWorkUserID) Then
                        Application.DoEvents()
                        LoadHistoryGrid(oRibs.GetActionHistory(CurrentID))
                        comAction.Text = ""
                        txtNote.Text = ""
                        Application.DoEvents()
                    End If

                End If

            End If
            'If CurrentUser <> comUser.Text Then
            'oRibs.LogAllocation(CurrentID, comUser.Text, True)
            'End If
            dsRibs = oRibs.GetRibsItem(CurrentID)
            BindRibsData()
DONOTHING:
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub mnuSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSave.Click
        Save()
    End Sub
    Private Sub SaveToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbSaveRecord.Click
        Save()
    End Sub

    Private Sub Cancel()
        Try
            bEditing = False
            ToggleTabDetail(False)
            ToggleTabContact(False)
            comAction.Text = ""
            txtNote.Text = ""
            ToggleScreenButtonsState(ScreenState.ViewData)
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub mnuCancelEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCancelEdit.Click
        Cancel()
    End Sub
    Private Sub CancelSaveToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbCancelCurrentEdit.Click
        Cancel()
    End Sub

    Private Sub RefreshToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRefresh.Click
        LoadRipsList()
    End Sub
    Private Sub RefreshToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbRefresh.Click
        LoadRipsList(txtFind.Text.Trim)
    End Sub

    Private Sub Filter()
        Try
            Dim f As New frmFilter
            f.Text = "Set Filter for: " & CurrentPC & "\" & CurrentUser
            f.ShowDialog()
            If f.DialogResult = Windows.Forms.DialogResult.OK Then
                If MsgBox("Refresh View?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Refresh") = MsgBoxResult.Yes Then
                    LoadRipsList()
                End If
            End If

        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub mnuFilter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFilter.Click
        Filter()
    End Sub
    Private Sub FilterToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbFilter.Click
        Filter()
    End Sub

    Private Sub About()
        Try
            Dim f As New frmAbout
            f.ShowDialog()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub mnuAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAbout.Click
        About()
    End Sub
    Private Sub HelpToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelpToolStripButton.Click
        About()
    End Sub

    Private Sub OpenDatabase()
        Try
            Dim sFileName As String = ""
            Dim oUserSec As New UserSecurity
            'If MsgBox("Create new database?", MsgBoxStyle.YesNo, "Database") = MsgBoxResult.Yes Then
            Dim oBrows As New OpenFileDialog
            oBrows.Title = "Please Select Database file "
            oBrows.Filter = "Access (*.mdb)|*.mdb"
            oBrows.InitialDirectory = My.Settings.ImportDataFolder
            oBrows.ShowDialog()
            sFileName = oBrows.FileName
            'Else
            'Dim oBrows As New OpenFileDialog
            'oBrows.Title = "Create new database file "
            'oBrows.Filter = "Access (*.mdb)|*.mdb"
            'oBrows.InitialDirectory = oSetting.ImportDataFolder
            'oBrows.ShowDialog()
            'sFileName = oBrows.FileName
            'End If

            If Trim(sFileName) <> "" Then
                My.Settings.AvailableDatabases = sFileName
                My.Settings.Save()
                Try
                    gConnectionString = GetdbConnection()
                    gConnectionStringArchive = gConnectionString.Replace("RIBS.Mdb", "RIBs_Archive.Mdb")
                    CurrentUser = Environ("USERNAME")
                    NetWorkUserID = Environ("USERNAME")
                    CurrentDB = My.Settings.AvailableDatabases
                    CurrentPC = Environ("COMPUTERNAME")
                    MainCaption = "RIBS -" & CurrentPC & "\" & CurrentUser & " [" & CurrentDB & "]"
                    Text = MainCaption
                    Application.DoEvents()
                    TestDBConnection()
                    CheckDbTables()
                    LoadRipsList()
                    GetUserList()
                Catch ex As Exception
                    DisplayErrors(ex)
                End Try
            End If
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub mnuOpenDatabase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuOpenDatabase.Click
        OpenDatabase()
    End Sub
    Private Sub OpenToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripButton.Click
        OpenDatabase()
    End Sub

    Private Sub Find()
        Try
            LoadRipsList(txtFind.Text.Trim)
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub tbFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbFind.Click
        Find()
    End Sub
    Private Sub mnuFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFind.Click
        Try
            Dim ofrm As New frmFind
            ofrm.txtFind.Text = txtFind.Text.Trim
            ofrm.ShowDialog()
            If ofrm.DialogResult = Windows.Forms.DialogResult.OK Then
                txtFind.Text = ofrm.txtFind.Text.Trim
                Find()
            Else
                Beep()
            End If
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Private Sub AddNew()
        Try
            If MsgBox("Add new Record?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Add New") = MsgBoxResult.Yes Then
                Dim oRibs As New RibsClass
                dsRibs = oRibs.GetRibsItem(ManualItems.AddNewManual)
                BindRibsData()
                AddHistoryRec()
                MsgBox("New Record Added", MsgBoxStyle.Information, "Done")
            End If

        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub
    Private Sub mnuAddNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAddNew.Click
        AddNew()
    End Sub
    Private Sub tbAddNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbAddNew.Click
        AddNew()
    End Sub

    Private Sub tbNewDataBase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbNewDataBase.Click
        Try
            If MsgBox("Creare new Database?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Create") = MsgBoxResult.Yes Then
                Dim oNewDb As New SaveFileDialog
                oNewDb.FileName = "NewRibs.mdb"

                oNewDb.Title = "Please Select Database file "
                oNewDb.Filter = "Access (*.mdb)|*.mdb"
                oNewDb.ShowDialog()
                If File.Exists(oNewDb.FileName) Then
                    If MsgBox("File exists, Overwrite?", MsgBoxStyle.YesNo + MsgBoxStyle.Question, "Overwrite") = MsgBoxResult.Yes Then
                        Kill(oNewDb.FileName)
                    Else
                        Exit Sub
                    End If
                End If

                'If CreateAccessDatabase(oNewDb.FileName) Then
                '    gConnectionString = Replace(gConnectionString, CurrentDB, oNewDb.FileName)
                '    If CreateAccessDatabaseDoWork() Then
                '        MsgBox("Database Created " & oNewDb.FileName, MsgBoxStyle.Information, "Done")
                '        LoadRipsList()
                '    Else
                '        MsgBox("Failed to create database Tables " & oNewDb.FileName, MsgBoxStyle.Critical, "Error")
                '    End If
                'Else
                '    MsgBox("Failed to create database " & oNewDb.FileName, MsgBoxStyle.Critical, "Error")
                'End If
            End If
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

#End Region

    Private Sub btnWorkFlow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWorkFlow.Click
        Try
            Dim oRibs As New RibsClass
            Dim f As New frmWorkFlow
            Dim ds As DataSet = oRibs.GetRibsItem(CurrentID)
            f.Text = "Work Flow Data"
            f.txtWorkFlow.Text = ""
            'For Each daCol As DataColumn In ds
            ' f.txtWorkFlow.Text += daCol.ColumnName & ":" & dsRibs.Tables("Ribs").Rows(0).Item(daCol.ColumnName) & vbCrLf
            'Next
            '
            f.txtWorkFlow.Text += "**********************************" & vbCrLf
            f.txtWorkFlow.Text += "POLICY NUMBER: " & vbTab & vbTab & ds.Tables("RIbs").Rows(0).Item("POLICY_NUMBER") & vbCrLf
            f.txtWorkFlow.Text += "CLIENT NAME: " & vbTab & vbTab & ds.Tables("RIbs").Rows(0).Item("MAILING_NAME") & vbCrLf
            f.txtWorkFlow.Text += "RETAINED: " & vbTab & vbTab & FormatCurrency(ds.Tables("RIbs").Rows(0).Item("Retained")) & vbCrLf
            f.txtWorkFlow.Text += "WRITE OFF: " & vbTab & vbTab & FormatCurrency(ds.Tables("RIbs").Rows(0).Item("WriteOff")) & vbCrLf
            f.txtWorkFlow.Text += "History: " & vbTab & vbTab & vbCrLf & vbCrLf
            For Each dr As DataRow In ds.Tables("ActionHistory").Rows
                f.txtWorkFlow.Text += "Action Date: " & vbTab & vbTab & dr.Item("ActionDate") & vbCrLf
                f.txtWorkFlow.Text += "Entry Date: " & vbTab & vbTab & dr.Item("EntryDate") & vbCrLf
                f.txtWorkFlow.Text += "Action: " & vbTab & vbTab & vbTab & dr.Item("Action") & vbCrLf
                f.txtWorkFlow.Text += "Status: " & vbTab & vbTab & vbTab & dr.Item("RibsState") & vbCrLf
                f.txtWorkFlow.Text += "Contact Method: " & vbTab & vbTab & dr.Item("ContactMethod") & vbCrLf
                f.txtWorkFlow.Text += "User: " & vbTab & vbTab & vbTab & UCase(dr.Item("User")) & vbCrLf
                f.txtWorkFlow.Text += "Note: " & vbTab & dr.Item("Note") & vbCrLf
                f.txtWorkFlow.Text += vbCrLf
            Next
            'f.txtWorkFlow.Text += "#################################" & vbCrLf
            'f.txtWorkFlow.Text += "<END>" & vbCrLf
            f.ShowDialog()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub


    Private Sub tbPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbPrint.Click
        Try
            Dim f As New frmPrint
            f.ShowDialog()
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Private Sub txtSuperInd_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSuperInd.TextChanged

    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveRecord.Click
        Save()
    End Sub

    Private Sub txtRetained_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtRetained.Validated, txtRetained.Validated
        sender.text = FormatCurrency(sender.Text, 2)
    End Sub

    Private Sub txtWriteoff_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtWriteoff.Validated
        sender.text = FormatCurrency(sender.Text, 2)
    End Sub

    Private Sub tbGetWork_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbGetWork.Click
        If oSec.CheckUserSecurity(NetWorkUserID, RIBS.UserSecurity.RIBSSecurityAction.EnterWorkLoadScreen) Then
            Dim oFrm As New frmWork
            oFrm.ShowDialog()
            LoadRipsList()
        Else
            SecurityMessage()
        End If
    End Sub

    Private Sub tbComBoUsers_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tbComBoUsers.TextChanged
        CurrentUser = tbComBoUsers.Text.ToUpper
        Dim oUser As New dbUser(CurrentUser, False)
        txtFind.Focus()
        Application.DoEvents()
        LoadRipsList()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddHistoryRec.Click
        AddHistoryRec()
    End Sub


    Private Sub txtNewAmount_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNewAmount.Validated
        sender.text = FormatCurrency(sender.Text, 2)
    End Sub

    Private Sub txtAmountDue_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtAmountDue.Validated
        sender.text = FormatCurrency(sender.Text, 2)
    End Sub

    Function FilterRIBS(ByVal ds As DataSet, ByVal rtType As ReturnType) As DataSet
        Try
            If txtFind.Text.Trim.Length > 0 Then Return ds
            Dim myFilter As String = ""
            If rtType = ReturnType.Main Then
                myFilter = oNetworkUser.MainFilter
                'myFilter = gsMyMainStates 12/01
            Else
                '12/01
                'myFilter = gsMyTaskStates
                myFilter = oNetworkUser.TaskFilter
            End If
            For Each dr As DataRow In ds.Tables("Ribs").Rows
                Dim dateD As Int32 = DateDiff(DateInterval.Day, dr("ActionDate"), CDate(FormatDateTime(Now(), DateFormat.ShortDate)))
                If rtType = ReturnType.Main Then
                    If dateD >= 0 Then
                        dr("IsRowVisible") = dr("IsRowVisible") + 1
                    Else

                    End If
                Else
                    If dateD < 0 Then
                        dr("IsRowVisible") = dr("IsRowVisible") + 1
                    Else

                    End If
                End If
                If InStr(myFilter, dr("RibsState") & ",") <> 0 Then
                    dr("IsRowVisible") = dr("IsRowVisible") + 1
                End If
                If dr("IsRowVisible") < 2 Then
                    dr.Delete()
                End If

            Next
            ds.Tables("Ribs").AcceptChanges()
            Return ds
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Private Sub txtPolicyNumber_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPolicyNumber.TextChanged
        lblPolicyNumber.Text = "Policy Number :" & txtPolicyNumber.Text
    End Sub

    Private Sub txtMailingName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMailingName.TextChanged
        lblMailingName.Text = "Client Name :" & txtMailingName.Text
    End Sub

    Private Sub tbTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim ofrm As New frmSearchFilter
        ofrm.ShowDialog()
    End Sub

    Private Sub tbSecurity_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbSecurity.Click
        Dim oSec As New UserSecurity
        If oSec.CheckUserSecurity(NetWorkUserID, RIBS.UserSecurity.RIBSSecurityAction.EditUsers) Then
            Dim oFrm As New frmUserSecurity
            oFrm.ShowDialog()
        Else
            SecurityMessage()
            If InputBox("Enter Admin Password", "Password", "Password") = "EnterNow1234" Then
                Dim oFrm As New frmUserSecurity
                oFrm.ShowDialog()
            End If
        End If

    End Sub

    Private Sub dgFullList_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgFullList.KeyUp
        ChangeCurrentItem()
        dgFullList.Focus()
    End Sub

    Sub CopyHistoryGridtoScreen()
        Try
            CurrentActionID = dgHistory.SelectedRows(0).Cells("ActionID").Value
            txtNote.Text = dgHistory.SelectedRows(0).Cells("Note").Value
            dtlDate.Text = dgHistory.SelectedRows(0).Cells("ActionDate").Value
            comAction.Text = dgHistory.SelectedRows(0).Cells("Action").Value
            comStatus.Text = dgHistory.SelectedRows(0).Cells("RibsState").Value
            comContactMethod.Text = dgHistory.SelectedRows(0).Cells("ContactMethod").Value
        Catch ex As Exception
        End Try

    End Sub

    Sub CheckHistorySecurity()
        Try

            If oSec.CheckUserSecurity(NetWorkUserID, RIBS.UserSecurity.RIBSSecurityAction.EditHistory) And _
                            UCase(dgHistory.SelectedRows(0).Cells("User").Value.ToString.ToUpper) = NetWorkUserID.ToUpper Then
                ToggleScreenButtonsState(ScreenState.CanAddRecordAndEditRecord)

            ElseIf oSec.CheckUserSecurity(NetWorkUserID, RIBS.UserSecurity.RIBSSecurityAction.EditOtherUserHistory) Then
                ToggleScreenButtonsState(ScreenState.CanAddRecordAndEditRecord)
            Else
                ToggleScreenButtonsState(ScreenState.ViewData)
            End If
        Catch ex As Exception
        End Try
        dgHistory.Focus()

    End Sub
    Private Sub dgHistory_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgHistory.MouseUp
        Try
            CopyHistoryGridtoScreen()
            CheckHistorySecurity()
            dgHistory.Focus()
        Catch ex As Exception
        End Try
    End Sub

    Private Sub btnEditCurrent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditCurrentRecord.Click
        EditCurrentHistory()
    End Sub
    Private Sub mnuEditSelected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuEditSelected.Click
        EditCurrentHistory()
    End Sub
    Private Sub tbEditRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbEditRecord.Click
        EditCurrentHistory()
    End Sub

    Sub DeleteHistory()
        Try
            If MsgBox("Are you sure you want to delete record " & vbCrLf & _
                                                dgHistory.SelectedRows(0).Cells("ActionDate").Value & vbCrLf & _
                                                dgHistory.SelectedRows(0).Cells("Note").Value, MsgBoxStyle.YesNo, "Delete") = MsgBoxResult.Yes Then
                Cursor = Cursors.WaitCursor
                Dim oRibs As New RibsClass
                oRibs.DeleteAction(CurrentActionID)
                Application.DoEvents()
                LoadHistoryGrid(oRibs.GetActionHistory(CurrentID))
                comAction.Text = ""
                txtNote.Text = ""
                Application.DoEvents()
            End If
            ToggleScreenButtonsState(ScreenState.ViewData)
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
        Cursor = Cursors.Default
    End Sub

    Private Sub dgHistory_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgHistory.KeyDown
        Try
            If e.KeyValue = Keys.Delete Then
                If oSec.CheckUserSecurity(NetWorkUserID, RIBS.UserSecurity.RIBSSecurityAction.DeleteHistory) And _
                        UCase(dgHistory.SelectedRows(0).Cells("User").Value) = NetWorkUserID.ToUpper Then
                    DeleteHistory()
                ElseIf oSec.CheckUserSecurity(NetWorkUserID, RIBS.UserSecurity.RIBSSecurityAction.EditOtherUserHistory) Then
                    DeleteHistory()
                Else
                    MsgBox("Can not delete another users data", MsgBoxStyle.Exclamation, "Delete")
                End If
                ToggleScreenButtonsState(ScreenState.ViewData)
            Else
                CopyHistoryGridtoScreen()
                CheckHistorySecurity()
            End If

        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Private Sub dgFullList_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgFullList.KeyDown
        Try
            If e.KeyValue = Keys.Delete Then
                Dim msg As String = ""
                If Not IsDBNull(dgFullList.SelectedRows(0).Cells("Policy_Number").Value) Then
                    msg = dgFullList.SelectedRows(0).Cells("Policy_Number").Value.ToString & vbCrLf
                End If
                If Not IsDBNull(dgFullList.SelectedRows(0).Cells("Mailing_Name").Value) Then
                    msg += dgFullList.SelectedRows(0).Cells("Mailing_Name").Value.ToString & vbCrLf
                End If
                If Not IsDBNull(dgFullList.SelectedRows(0).Cells("Mailing_Name").Value) Then
                    msg += dgFullList.SelectedRows(0).Cells("Mailing_Name").Value.ToString & vbCrLf
                End If
                If Not IsDBNull(dgFullList.SelectedRows(0).Cells("LETTER_DATE").Value) Then
                    msg += FormatDateTime(dgFullList.SelectedRows(0).Cells("LETTER_DATE").Value, DateFormat.ShortDate)
                End If

                If oSec.CheckUserSecurity(NetWorkUserID, RIBS.UserSecurity.RIBSSecurityAction.DeleteMainRec) Then
                    If MsgBox("Are you sure you want to delete record?" & vbCrLf & _
                                "CAN NOT Undo! All history will be deleted! " & vbCrLf & vbCrLf & msg _
                                                , MsgBoxStyle.YesNo, "Delete") = MsgBoxResult.Yes Then
                        Cursor = Cursors.WaitCursor
                        Dim oRibs As New RibsClass
                        oRibs.DeleteLetter(CurrentID)
                        LoadRipsList()
                    End If
                Else
                    MsgBox("Can not delete main data", MsgBoxStyle.Exclamation, "Delete")
                End If
                ToggleScreenButtonsState(ScreenState.ViewData)
            End If
        Catch ex As Exception
            DisplayErrors(ex)
        End Try
    End Sub

    Private Sub txtFind_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFind.KeyUp
        If e.KeyCode = Keys.Enter Then
            Find()
        End If

    End Sub

    Sub LoadDropDownBoxes()
        Try
            Dim oRibs As New RibsClass
            Dim dr As DataRow
            txtNote.Text = ""

            comStatus.Items.Clear()
            For Each dr In oRibs.GetRibsStates.Rows
                comStatus.Items.Add(dr(0))
            Next
            comAction.Text = ""
            comAction.Items.Clear()
            For Each dr In oRibs.GetRibsActions.Rows
                comAction.Items.Add(dr("Action"))
            Next

            comContactMethod.Text = ""
            comContactMethod.Items.Clear()
            For Each dr In oRibs.GetContactMethods.Rows
                comContactMethod.Items.Add(dr("ContactMethod"))
            Next

            comNoticeCode.Items.Clear()
            For Each dr In oRibs.GetNoticeCode.Rows
                comNoticeCode.Items.Add(dr("Letter_Code"))
            Next

        Catch ex As Exception
            DisplayErrors(ex)
        End Try

    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Dim o As New RibsDataImportClass
        o.ArchiveData()
    End Sub

    Private Sub comData_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comData.TextChanged
        LoadRipsList(txtFind.Text.Trim)
    End Sub

    Private Sub gdHist_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gdHist.CellDoubleClick
        Try
            txtFind.Text = gdHist.SelectedRows(0).Cells("POLICY_NUMBER").Value
            LoadRipsList(txtFind.Text.Trim)
        Catch ex As Exception

        End Try
    End Sub

    Private Sub gdHist_ColumnDisplayIndexChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles gdHist.ColumnDisplayIndexChanged
        SaveGridSetting()
    End Sub

    Private Sub gdHist_ColumnWidthChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles gdHist.ColumnWidthChanged
        SaveGridSetting()
    End Sub
End Class